package com.zl.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sun.org.apache.xpath.internal.axes.SubContextList;
import com.zl.common.Constant;
import com.zl.common.enumType.Category;
import com.zl.common.enumType.Column;
import com.zl.common.enumType.PublicDate;
import com.zl.common.thread.TokenThread;
import com.zl.entity.Area;
import com.zl.entity.City;
import com.zl.entity.Collect;
import com.zl.entity.Entity;
import com.zl.entity.Member;
import com.zl.entity.NewsEntity;
import com.zl.entity.Province;
import com.zl.entity.QueryEntity;
import com.zl.entity.Role;
import com.zl.entity.SubscribeEntity;
import com.zl.service.AreaService;
import com.zl.service.CollectService;
import com.zl.service.MemberService;
import com.zl.service.SelectorService;
import com.zl.service.SubscribeService;
import com.zl.util.JsonMapper;
import com.zl.util.SearchUtils;
import com.zl.weixin.entity.AccessToken;
import com.zl.weixin.entity.UserClient;
import com.zl.weixin.util.WeixinUtil;

/**   
* @Title: SubscribeController.java 
* @Package com.zl.controller 
* @Description: 订阅控制器
* @author chxl   
* @date 2015年8月10日 下午5:56:50 
* @version V1.0   
*/
@Controller
@RequestMapping("subscribe")
@Scope("prototype")
public class SubscribeController {
	
	@Autowired
	private SelectorService selectorService;
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private CollectService collectService;
	@Autowired
	private AreaService areaService;
	
	@RequestMapping("rule")
	public String rule(Model model,HttpServletRequest request){
		String code = request.getParameter("code");//通过微信回调得到的参数
		String appId = "wxac9a290c5dc49ed0";
    	// 第三方用户唯一凭证密钥
    	String appSecret = "24dd8e15cfeb82fc1c0ac60c8705d75c";
    	UserClient user = new UserClient();
    	if(StringUtils.isNotBlank(code)){
    		String openId = WeixinUtil.getOpenId(appId, appSecret, code).getOpenid();//通过code调取openid
    		AccessToken at = TokenThread.accessToken;
        	if(at!=null){
        		if(request.getSession().getAttribute("user")==null){
        			if(StringUtils.isBlank(openId)){
        				return "";
        			}
        			user= WeixinUtil.getUser(at.getToken(), openId);
	        		request.getSession().setAttribute("user", user); //将对象放入session中
	    		}else{
	    			user = (UserClient)request.getSession().getAttribute("user");
	    		}//将对象放入session中
        		
        	}else{
        		TokenThread.accessToken = WeixinUtil.getAccessToken(appId, appSecret); 
        		at = TokenThread.accessToken;
        		if(request.getSession().getAttribute("user")==null){
        			if(StringUtils.isBlank(openId)){
        				return "";
        			}
        			user= WeixinUtil.getUser(at.getToken(), openId);
	        		request.getSession().setAttribute("user", user); //将对象放入session中
	    		}else{
	    			user = (UserClient)request.getSession().getAttribute("user");
	    		}
        	}
    	}else{
			user = (UserClient)request.getSession().getAttribute("user");
    	}
    	
		List<Province> provinceList = selectorService.getAllProvince();
		model.addAttribute("provinceList", provinceList);
		
		List<Entity> categoryList  = selectorService.getCategoryList();
		List<Entity> columnList = selectorService.getColumnList();
		List<Entity> publicDateList = selectorService.getPublicDateList();
		
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("columnList",columnList);
		model.addAttribute("publicDateList",publicDateList);
		
//		UserClient user = new UserClient();
//		user.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
		//request.getSession().setAttribute("user", user);
		//UserClient user = (UserClient)request.getSession().getAttribute("user");
		String openid = user.getOpenid();
		List<SubscribeEntity> list = subscribeService.getSubEntity(openid);
		model.addAttribute("sublist", list);
		return "rss_rule";
	}
	
	@RequestMapping("index")
	public String index(Model model,HttpServletRequest request){
		String code = request.getParameter("code");//通过微信回调得到的参数
		String appId = "wxac9a290c5dc49ed0";
    	// 第三方用户唯一凭证密钥
    	String appSecret = "24dd8e15cfeb82fc1c0ac60c8705d75c";
    	UserClient user = new UserClient();
    	if(StringUtils.isNotBlank(code)){
    		String openId = WeixinUtil.getOpenId(appId, appSecret, code).getOpenid();//通过code调取openid
    		AccessToken at = TokenThread.accessToken;
        	if(at!=null){
        		if(request.getSession().getAttribute("user")==null){
        			if(StringUtils.isBlank(openId)){
        				return "";
        			}
        			user= WeixinUtil.getUser(at.getToken(), openId);
	        		request.getSession().setAttribute("user", user); //将对象放入session中
	    		}else{
	    			user = (UserClient)request.getSession().getAttribute("user");
	    		}//将对象放入session中
        		
        	}else{
        		TokenThread.accessToken = WeixinUtil.getAccessToken(appId, appSecret); 
        		at = TokenThread.accessToken;
        		if(request.getSession().getAttribute("user")==null){
        			if(StringUtils.isBlank(openId)){
        				return "";
        			}
        			user= WeixinUtil.getUser(at.getToken(), openId);
	        		request.getSession().setAttribute("user", user); //将对象放入session中
	    		}else{
	    			user = (UserClient)request.getSession().getAttribute("user");
	    		}
        	}
    	}else{
			user = (UserClient)request.getSession().getAttribute("user");
    	}
//		UserClient user = new UserClient();
//		user.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
//		request.getSession().setAttribute("user", user);
		List<Entity> publicDateList = selectorService.getPublicDateList();
		 
		if(user==null){
			return "";//返回用户取不到页面
		}
		String openid = user.getOpenid();
		List<SubscribeEntity> list = subscribeService.getSubEntity(openid);
		
		model.addAttribute("publicDateList",publicDateList);
		model.addAttribute("subscribes", list);
		return "rss_li";
	}
	
	@RequestMapping("list")
	@ResponseBody
	public String list(HttpServletRequest request){
		
		UserClient user = (UserClient)request.getSession().getAttribute("user");
		int subPage = Integer.parseInt(request.getParameter("subType"));
		int page = Integer.parseInt(request.getParameter("page"));
		String publicDateValue = request.getParameter("publicDateValue");
		String keywords = request.getParameter("keywords");
		 
		String openid = user.getOpenid();
		List<SubscribeEntity> list = subscribeService.getSubscribeByOpenId(openid);
		List<NewsEntity> newsList = new ArrayList<NewsEntity>();
		if(subPage==0){
			List<QueryEntity> querylist = new ArrayList<QueryEntity>();
			for(SubscribeEntity subscribeEntity:list){
				QueryEntity queryEntity = new QueryEntity();
				queryEntity.setPage(page);
				if(StringUtils.isNotBlank(keywords)){
					queryEntity.setKeywords(subscribeEntity.getKeywords()+" "+keywords);
				}else{
					queryEntity.setKeywords(subscribeEntity.getKeywords());
				}
				
				queryEntity.setCategory(subscribeEntity.getCategory());
				queryEntity.setColumn(subscribeEntity.getColumn());
				queryEntity.setPublicDateValue(publicDateValue);//前台选择的时间
				queryEntity.setArea(subscribeEntity.getArea());
				querylist.add(queryEntity);
			}
			
			newsList = SearchUtils.search(querylist);
		}else{
			SubscribeEntity subscribeEntity = list.get(subPage-1);
			QueryEntity queryEntity = new QueryEntity();
			queryEntity.setPage(page);
			if(StringUtils.isNotBlank(keywords)){
				queryEntity.setKeywords(subscribeEntity.getKeywords()+" "+keywords);
			}else{
				queryEntity.setKeywords(subscribeEntity.getKeywords());
			}
			queryEntity.setCategory(subscribeEntity.getCategory());
			queryEntity.setColumn(subscribeEntity.getColumn());
			queryEntity.setPublicDateValue(publicDateValue);//前台选择的时间
			queryEntity.setArea(subscribeEntity.getArea());
			newsList = SearchUtils.search(queryEntity);
		}
		
		for(NewsEntity newsEntity:newsList){
			List<Collect> collectList = collectService.isExist(user.getOpenid(), newsEntity.getId());
			if(collectList!=null&&collectList.size()>0){
				newsEntity.setCollections("1");
			}else{
				newsEntity.setCollections("0");
			}
		}
		String str =  JsonMapper.nonDefaultMapper().toJson(newsList);
		return "{\"success\":\"true\",\"msg\":"+str+"}";
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("save")
	@ResponseBody
	public String save(HttpServletRequest request,SubscribeEntity subscribeEntity){
		UserClient user = (UserClient)request.getSession().getAttribute("user");
//		UserClient user = new UserClient();
//		user.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
		if(user==null){
			return "";
		}
		
		String openid = user.getOpenid();
		Member member = memberService.getMemberByOpenId(openid);
		Role role = member.getRole();//得到用户权限
		List<SubscribeEntity> list = subscribeService.getSubscribeByOpenId(openid);
		int roleSubCount = Integer.parseInt(role.getSubCount());
		
		Map<String,String> result = new HashMap<String,String>();
		
		if(list.size() >= roleSubCount){
			result.put("type", "0");
			result.put("msg", "订阅失败，"+role.getRoleName()+"只能订阅"+roleSubCount+"条");
			return JsonMapper.nonDefaultMapper().toJson(result);
		}else{
			if(StringUtils.isNotBlank(subscribeEntity.getId())){
				subscribeService.updateSubscribe(subscribeEntity);
				result.put("type", "1");
				result.put("msg", "修改成功");
				return JsonMapper.nonDefaultMapper().toJson(result);
			}else{
				subscribeEntity.setId(UUID.randomUUID().toString());
				subscribeEntity.setOpenid(openid);
				subscribeEntity.setCreateTime(new Date());
				subscribeService.insertSubscribe(subscribeEntity);
				result.put("type", "1");
				result.put("msg", "订阅成功");
				return JsonMapper.nonDefaultMapper().toJson(result);
			}
			
		}
		
	}
	
	@RequestMapping("deleteById")
	@ResponseBody
	public String deleteById(String id){
		Map<String,String> result = new HashMap<String,String>();
		subscribeService.deleteById(id);
		result.put("type", "1");
		result.put("msg", "删除成功");
		return JsonMapper.nonDefaultMapper().toJson(result);
	}
	
	@RequestMapping("updateById")
	public String updateById(Model model,String id,HttpServletRequest request){
		SubscribeEntity subscribe = subscribeService.selectById(id);
		model.addAttribute("subscribeEntity", subscribe);
		List<Province> provinceList = selectorService.getAllProvince();
		model.addAttribute("provinceList", provinceList);
		
		List<Entity> categoryList  = selectorService.getCategoryList();
		List<Entity> columnList = selectorService.getColumnList();
		List<Entity> publicDateList = selectorService.getPublicDateList();
		
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("columnList",columnList);
		model.addAttribute("publicDateList",publicDateList);
		
//		UserClient user = new UserClient();
//		user.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
		//request.getSession().setAttribute("user", user);
		UserClient user = (UserClient)request.getSession().getAttribute("user");
		String openid = user.getOpenid();
		List<SubscribeEntity> list = subscribeService.getSubEntity(openid);
		model.addAttribute("sublist", list);
		
		String place = subscribe.getArea();
		String placeType = subscribe.getAreaType();
		Area area = areaService.getArea(placeType, place);
		model.addAttribute("area", area);
		
		String category = subscribe.getCategory();
		String categoryStr = "";
		for(Category t:Category.values()){
			if(category.contains(t.getCode())){
				category = category.replace(t.getCode(), t.getName());
			}
		}
		categoryStr = category;
		model.addAttribute("categoryStr",categoryStr);
		
		String column = subscribe.getColumn();
		String columnStr = "";
		for(Column c:Column.values()){
			if(column.contains(c.getCode())){
				column = column.replace(c.getCode(), c.getName());
			}
		}
		columnStr = column;
		model.addAttribute("columnStr",columnStr);
		
		return "rss_rule_modify";
	}
}
